package socket

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)

var myUpgrade = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true // 或者根据需要检查 Origin
	},
}

// 全局连接变量
var localConnections = make(map[string]*websocket.Conn)

// Handle SocketHandle 处理socket
func Handle(c *gin.Context) {
	//获取websocket连接
	conn, err := myUpgrade.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	//defer conn.Close()

	//将连接保存进全局变量中
	localConnections[conn.RemoteAddr().String()] = conn
	go read(conn)

	//fmt.Println(conn.LocalAddr())
	//fmt.Println(conn.RemoteAddr().String())

	//fun := conn.PingHandler()
	//err = fun("ping")
	//if err != nil {
	//	fmt.Println(err)
	//	return
	//}

	//err = conn.WriteJSON("hello word")
	//if err != nil {
	//	fmt.Println(err)
	//	return
	//}
}
